/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.nls.support;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import org.vacoor.nothing.common.json.Jacksons;
import org.vacoor.nothing.common.util.HttpUtils;
import org.vacoor.nothing.common.util.IOUtils;
import org.vacoor.nothing.common.util.StringUtils;
import org.vacoor.nothing.security.nls.TranslationException;
import org.vacoor.nothing.security.nls.Translator;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;

/**
 * 百度翻译引擎 - 基于百度翻译API
 * http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3%E9%A6%96%E9%A1%B5/%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91/%E7%BF%BB%E8%AF%91API
 *
 * @author vacoor
 */
public class BaiduTranslator extends TranslatorSupport {
    private static final String BAIDU_API = "http://openapi.baidu.com/public/2.0/bmt/translate";
    public static final String BD_AK_PROP = "baidu.ak";
    public static final Translator INSTANCE = new BaiduTranslator();

    @Override
    public boolean accepts(Locale from, Locale to) {
        return true;
    }

    @Override
    protected String doTranslate(String text, Locale from, Locale to, Properties props) {
        LOG.debug("执行百度翻译: {}, {} -> {}", text, from, to);
        String appKey = props.getProperty(BD_AK_PROP, "");
        if (!StringUtils.hasText(appKey)) {
            // TODO 我晕, 好像只有有 client_id=这个参数就行
            // throw new TranslationException("baidu.ak must be not empty");
        }

        try {
            InputStream is = HttpUtils.get(BAIDU_API, ImmutableMap.of(
                    "client_id", appKey,
                    "q", text,
                    "from", from.getLanguage(),
                    "to", to.getLanguage()
            ), 10 * 1000);

            text = IOUtils.readText(is, Charsets.UTF_8, true);
            JsonNode root = Jacksons.deserialize(text, JsonNode.class);
            JsonNode error_code = root.get("error_code");
            if (null == error_code) {
                JsonNode result = root.get("trans_result");
                for (JsonNode r : result) {
                    // String from = r.get("src").asText();
                    String dst = r.get("dst").asText();

                    return dst;
                }
            } else {
                String msg = root.get("error_msg").asText();
                throw new TranslationException(msg + "(" + error_code.asText() + ")");
            }
        } catch (IOException e) {
            throw new TranslationException(e);
        }
        return null;
    }
}
